package top.ajunnihao.core.util.resp;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * TODO 封装 Rest 应答 -- 错误响应(不需要写 @ResponseBody)
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/26
 */
public class RestError implements View {

    private Object data;
    private String message;
    private static RestError restError;

    private RestError() {

    }

    private RestError(Object data) {
        this.data = data;
    }

    private RestError(String message) {
        this.message = message;
    }

    private RestError(Object data, String message) {
        this.data = data;
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public String getMessage() {
        return message;
    }

    public static RestError fail() {
        if (restError == null) {
            restError = new RestError();
        }
        return restError;
    }

    public static RestError fail(Object data) {
        if (restError == null) {
            restError = new RestError(data);
        }
        return restError;
    }

    public static RestError fail(String message) {
        if (restError == null) {
            restError = new RestError(message);
        }
        return restError;
    }

    public static RestError fail(Object data, String message) {
        if (restError == null) {
            restError = new RestError(data, message);
        }
        return restError;
    }

    @Override
    public void render(Map<String, ?> map,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        BaseResp jResp;
        if (message != null && !message.isEmpty()) {
            if (data == null) {
                jResp = JResp.fail(message);
            } else {
                if (data instanceof JSON) {
                    // 本身就是 JSONObject 或 JSONArray
                    jResp = JResp.fail(data, message);
                } else {
                    jResp = JResp.fail(JSON.toJSON(data), message);
                }
            }
        } else {
            if (data == null) {
                jResp = JResp.fail();
            } else {
                if (data instanceof JSON) {
                    // 本身就是 JSONObject 或 JSONArray
                    jResp = JResp.fail(data);
                } else {
                    jResp = JResp.fail(JSON.toJSON(data));
                }
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain");
        response.getWriter().print(JSON.toJSONString(jResp));
    }


}
